# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-05 23:12
# File     : main.py
# Project  : codebuddy_craft
# Desc     :

# backend/main.py
"""
FastAPI 主应用 🚀

CodeBuddy Craft 后端服务入口
"""

import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from backend.core.config import get_app_settings
from backend.database.connection import init_db
from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
import time

from backend.utils.config import settings
from backend.utils.logger import get_logger
from backend.utils.log_utils import RequestLoggingMiddleware
from backend.database import init_db, close_database
from backend.api import (
    auth_routes,
    user_routes,
    project_routes,
    file_routes,
    code_routes,
    chat_routes,
    websocket_routes
)

logger = get_logger(__name__)

# 加载配置
settings = get_app_settings()

@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时
    logger.info("🚀 CodeBuddy Craft 正在启动...")

    try:
        # 初始化数据库
        await init_db()
        logger.success("数据库初始化完成")

        # 其他初始化操作
        logger.success("应用启动完成")

    except Exception as e:
        logger.error(f"应用启动失败: {str(e)}")
        raise

    yield

    # 关闭时
    logger.info("🛑 CodeBuddy Craft 正在关闭...")
    try:
        await close_database()
        logger.success("应用关闭完成")
    except Exception as e:
        logger.error(f"应用关闭错误: {str(e)}")


# # 创建FastAPI应用
# app = FastAPI(
#     title=settings.PROJECT_NAME,
#     description=settings.DESCRIPTION,
#     version=settings.VERSION,
#     docs_url="/docs" if settings.is_development() else None,
#     redoc_url="/redoc" if settings.is_development() else None,
#     lifespan=lifespan
# )

# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    debug=settings.DEBUG,
    docs_url="/docs" if settings.is_development else None,
    redoc_url="/redoc" if settings.is_development else None
)

# # 中间件配置
# if settings.CORS_ORIGINS:
#     app.add_middleware(
#         CORSMiddleware,
#         allow_origins=settings.CORS_ORIGINS,
#         allow_credentials=settings.CORS_ALLOW_CREDENTIALS,
#         allow_methods=settings.CORS_ALLOW_METHODS,
#         allow_headers=settings.CORS_ALLOW_HEADERS,
#     )

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=settings.CORS_METHODS,
    allow_headers=settings.CORS_HEADERS,
)

# 添加Gzip压缩
app.add_middleware(GZipMiddleware, minimum_size=1000)

# 添加请求日志中间件
app.add_middleware(RequestLoggingMiddleware)

# 静态文件服务
if settings.is_development():
    app.mount("/static", StaticFiles(directory="static"), name="static")


# 全局异常处理
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    """HTTP异常处理"""
    logger.warning(f"HTTP异常: {exc.status_code} - {exc.detail}")
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "error": {
                "code": exc.status_code,
                "message": exc.detail,
                "timestamp": time.time()
            }
        }
    )


@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    """通用异常处理"""
    logger.error(f"未处理异常: {str(exc)}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content={
            "error": {
                "code": 500,
                "message": "内部服务器错误" if settings.is_production() else str(exc),
                "timestamp": time.time()
            }
        }
    )


# 健康检查
@app.get("/health")
async def health_check():
    """健康检查端点"""
    try:
        from backend.database.connection import health_check
        db_status = await health_check()

        return {
            "status": "healthy",
            "timestamp": time.time(),
            "version": settings.VERSION,
            "environment": settings.ENVIRONMENT,
            "database": db_status
        }
    except Exception as e:
        logger.error(f"健康检查失败: {str(e)}")
        return JSONResponse(
            status_code=503,
            content={
                "status": "unhealthy",
                "timestamp": time.time(),
                "error": str(e)
            }
        )


# 根路径
@app.get("/")
async def root():
    """根路径响应"""
    return {
        "message": "🎉 欢迎使用 CodeBuddy Craft API",
        "version": settings.VERSION,
        "docs": "/docs" if settings.is_development() else None,
        "health": "/health"
    }


# API路由注册
app.include_router(auth_routes.router, prefix=f"{settings.API_V1_STR}/auth", tags=["认证"])
app.include_router(user_routes.router, prefix=f"{settings.API_V1_STR}/users", tags=["用户"])
app.include_router(project_routes.router, prefix=f"{settings.API_V1_STR}/projects", tags=["项目"])
app.include_router(file_routes.router, prefix=f"{settings.API_V1_STR}/files", tags=["文件"])
app.include_router(code_routes.router, prefix=f"{settings.API_V1_STR}/code", tags=["代码"])
app.include_router(chat_routes.router, prefix=f"{settings.API_V1_STR}/chat", tags=["对话"])
app.include_router(websocket_routes.router, prefix="/ws", tags=["WebSocket"])

if __name__ == "__main__":
    # import uvicorn
    #
    # uvicorn.run(
    #     "backend.main:app",
    #     host=settings.HOST,
    #     port=settings.PORT,
    #     reload=settings.is_development(),
    #     log_level="info"
    # )
    uvicorn.run(
        "main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.RELOAD and settings.is_development,
        workers=settings.WORKERS if settings.is_production else 1,
        log_level=settings.LOG_LEVEL.lower()
    )
